// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace GroceryList
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        NewItemWindow _newItemWindow;

        public MainWindow()
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;

            InitializeComponent();

            // Creates a CloudList<GroceryItem> and posts back a delegate to do the databinding on the UI thread.
            App.InitializeGroceriesAsync(GroceryItemsListBox);
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            if (_newItemWindow == null)
                _newItemWindow = new NewItemWindow();
            _newItemWindow.Show();
        }

        private void BoughtButton_Click(object sender, RoutedEventArgs e)
        {
            if (GroceryItemsListBox.SelectedIndex < 0)
                return;

            App.Groceries.RemoveAt(GroceryItemsListBox.SelectedIndex);
        }

        protected override void OnClosed(EventArgs e)
        {
            App.Groceries.Dispose();  // Unsubscribe from updates.

            if (_newItemWindow != null)
                _newItemWindow.Close();
            base.OnClosed(e);
        }

        void UnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
        {
            String message = String.Format("Unhandled exception: {0}  {1}", e.ExceptionObject.GetType(), ((Exception)e.ExceptionObject).Message);
            MessageBox.Show(message, "Unhandled exception in GroceryList sample", MessageBoxButton.OKCancel);
        }

        private async void ResetButton_Click(object sender, RoutedEventArgs e)
        {
            if (App.Groceries == null)
                return;  // Avoid a race where someone attempts to click on this button before our grocery list is initialized.

            // We can call either Clear() or await ClearAsync().  We should await async operations to ensure we do not block the UI thread.
            await App.Groceries.ClearAsync();
            App.AddDefaultItems();            
        }
    }
}
